#include "raylib.h"
#include <iostream>
#include <string>
#include <vector>
#include <thread>
#include <algorithm>
using namespace std;

// 函数声明
Texture initTexture(const string& imgPath);
vector<Rectangle> getFrames(int direction, int frameWidth, int frameHeight, int frameCount);
void changeDirection(int direction,vector<Rectangle> &actionFrames,int frameWidth, int frameHeight, int frameCount);
void run_right(float &x,float &y,float step,int frameWidth, int frameHeight);
void run_down(float &x,float &y,float step,int frameWidth, int frameHeight);
void run_left(float &x,float &y,float step,int frameWidth, int frameHeight);
void run_up(float &x,float &y,float step,int frameWidth, int frameHeight);
void character_thread(int id);

int frameCount;
int frameWidth;
int frameHeight;
int direction;
bool flag;
bool moving;
float x;
float y;
float step;

void character_thread(int id)
{
    vector<int> activeDirections;
    moving = false;
    while(flag)
    {
         // 检测按键按下，添加到数组,当遍历到end时即代表没找到
        if(IsKeyDown(KEY_W) && 
           find(activeDirections.begin(), activeDirections.end(), 0) == activeDirections.end()) {
            activeDirections.push_back(0);
            moving=true;
        }
        if(IsKeyDown(KEY_D) && 
           find(activeDirections.begin(), activeDirections.end(), 1) == activeDirections.end()) {
            activeDirections.push_back(1);
            moving=true;
        }
        if(IsKeyDown(KEY_S) && 
           find(activeDirections.begin(), activeDirections.end(), 2) == activeDirections.end()) {
            activeDirections.push_back(2);
            moving=true;
        }
        if(IsKeyDown(KEY_A) && 
           find(activeDirections.begin(), activeDirections.end(), 3) == activeDirections.end()) {
            activeDirections.push_back(3);
            moving=true;
        }
        
        // 检测按键释放，从数组中移除，
        if(IsKeyUp(KEY_W)) {
            auto it = find(activeDirections.begin(), activeDirections.end(), 0);
            if (it != activeDirections.end()) {
                activeDirections.erase(it);
            }
        }
        if(IsKeyUp(KEY_D)) {
            auto it = find(activeDirections.begin(), activeDirections.end(), 1);
            if (it != activeDirections.end()) {
                activeDirections.erase(it);
            }
        }
        if(IsKeyUp(KEY_S)) {
            auto it = find(activeDirections.begin(), activeDirections.end(), 2);
            if (it != activeDirections.end()) {
                activeDirections.erase(it);
            }
        }
        if(IsKeyUp(KEY_A)) {
            auto it = find(activeDirections.begin(), activeDirections.end(), 3);
            if (it != activeDirections.end()) {
                activeDirections.erase(it);
            }
        }
        
        // 如果有按下的方向键，使用最后一个作为基准方向并移动
        if (!activeDirections.empty()) {
            int lastDirection = activeDirections.back();  // 获取最后按下的方向
            direction = lastDirection;  // 更新全局方向
            
            // 根据最后按下的方向移动
            switch (lastDirection) {
                case 0: // W - 上
                    run_up(x, y, step, frameWidth, frameHeight);
                    break;
                case 1: // D - 右
                    run_right(x, y, step, frameWidth, frameHeight);
                    break;
                case 2: // S - 下
                    run_down(x, y, step, frameWidth, frameHeight);
                    break;
                case 3: // A - 左
                    run_left(x, y, step, frameWidth, frameHeight);
                    break;
            }
        }
        if(IsKeyUp(KEY_A)&&IsKeyUp(KEY_D)&&IsKeyUp(KEY_S)&&IsKeyUp(KEY_W))
            moving =false;
        this_thread::sleep_for(chrono::milliseconds(10));
    
    }
}



int main()
{
    InitWindow(2000, 1500, "角色动画演示");
    SetTargetFPS(120);

    flag=true;

    // 加载角色精灵图
    string imgPath = "../assets/imgs/characters/character.png";
    Texture chara_texture = initTexture(imgPath);

    // 计算帧尺寸
    frameCount = 3;                  // 总帧数
    frameWidth = 100;  // 自动计算单帧宽度
    frameHeight = 100;          // 假设4行动画
    cout<<frameWidth<<"  "<<frameHeight<<endl;
    // 获取动画帧
    vector<Rectangle> actionFrames = getFrames(2, frameWidth, frameHeight, frameCount);
    // 动画参数
    int currentFrame = 0;
    float frameTime = 0.2f;  // 每帧停留时间
    float frameTimer = 0.0f; // 动画帧时长计时器
    
    x=0.0f;
    y=0.0f;
    direction=0;
    float moveSpeed=900.0f;

      // 固定绘制位置

    std::thread s1(character_thread,1);
    //主要循环
    while (!WindowShouldClose())
    {
        step=moveSpeed*0.016;
        changeDirection(direction,actionFrames, frameWidth, frameHeight, frameCount);
        // 帧切换逻辑
        if(moving){
            frameTimer += 0.016;
            if (frameTimer >= frameTime)
            {
                currentFrame = (currentFrame + 1) % frameCount;
                frameTimer = 0;
            }
        }
        Vector2 drawPosition = {x, y};
        // 绘制
        BeginDrawing();
        ClearBackground(WHITE);
        
        // 绘制当前帧
        DrawTextureRec(chara_texture, actionFrames[currentFrame], drawPosition, WHITE);
        
        // 调试信息
        DrawText(TextFormat("帧尺寸: %dx%d", frameWidth, frameHeight), 10, 10, 20, BLACK);
        DrawText(TextFormat("当前帧数: %d", currentFrame), 10, 40, 20, BLACK);
        DrawText(TextFormat("位置: %d,%d", (int)x,(int)y), 10, 60, 20, BLACK);
        // this_thread::sleep_for(chrono::milliseconds(10));
        EndDrawing();
    }
    
    flag = false;
    
    // 2. 等待线程结束
    if (s1.joinable()) {
        cout << "等待线程结束..." << endl;
        s1.join();  // 等待线程安全退出
        cout << "线程已结束" << endl;
    }
    UnloadTexture(chara_texture);
    CloseWindow();
    return 0;
}

// 初始化纹理，使用const引用避免复制
Texture initTexture(const string& imgPath){
    // 使用c_str()正确获取C风格字符串
    Image character = LoadImage(imgPath.c_str());
    ImageResize(&character, 300, 400);
    Texture chara_texture = LoadTextureFromImage(character);
    // SetTextureFilter(chara_texture,TEXTURE_FILTER_POINT);
    UnloadImage(character);
    return chara_texture;
}

/**
 * 获取动画帧的属性，即动画图的范围
 * @param direction 方向（用于计算Y坐标）
 * @param frameWidth 帧宽度
 * @param frameHeight 帧高度
 * @param frameCount 帧数
 * @return 动画帧的vector容器
 */
vector<Rectangle> getFrames(int direction, int frameWidth, int frameHeight, int frameCount){
    vector<Rectangle> frames;
    frames.reserve(frameCount); // 预留空间提高效率
    
    // 根据方向计算Y坐标（不同方向对应不同行）
    int directions[4]={3,2,0,1};
    float yPos = directions[direction] * frameHeight;
    
    for (int i = 0; i < frameCount; i++)
    {
        frames.push_back({
            (float)(i * frameWidth),  // X坐标
            yPos,                     // Y坐标（根据方向变化）
            (float)frameWidth,        // 宽度
            (float)frameHeight        // 高度
        });
    }
    return frames;
}

void changeDirection(int direction,vector<Rectangle> &actionFrames,int frameWidth, int frameHeight, int frameCount)
{
    actionFrames=getFrames(direction,frameWidth,frameHeight,frameCount);
}

void run_right(float &x,float &y,float step,int frameWidth, int frameHeight)
{
    x+=step;
    if(x>1920)
        x=1920;
}
void run_up(float &x,float &y,float step,int frameWidth, int frameHeight)
{
    y-=step;
    if(y<0)
        y=0;
}
void run_down(float &x,float &y,float step,int frameWidth, int frameHeight)
{
    y+=step;
    if((y+frameHeight)>1500)
        y=1500-frameHeight;
}
void run_left(float &x,float &y,float step,int frameWidth, int frameHeight)
{
    x-=step;
    if(x<0)
        x=0;
}
